package com.gss.module.generator.core;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import com.gss.common.utils.StringUtils;
import com.gss.module.generator.constants.CommonConstants;
import com.gss.module.generator.constants.TemplateEnum;
import com.gss.module.generator.entity.BaseEntity;
import com.gss.module.generator.entity.DefaultConfigInfo;
import com.gss.module.generator.entity.FieldEntity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author: DYang
 * @since: 2023/5/26
 * @description:
 */
public class ControllerGenerator {

    private static  String CONTROLLER_PATH = "classpath:template/ControllerGeneratorTemplate.template";

    /**
     * 根据内如构建实体类
     * @param baseEntity
     */
    public static boolean builder(String fileDir,BaseEntity baseEntity){
        //构建实体类
        String content = buildController(baseEntity,CONTROLLER_PATH);
        if (content == null){
            System.out.println("模板不存在，暂未解析到数据");
            return false;
        }
        //存储到指定指定文件
        saveEntityFile(baseEntity.getClassName(),content,fileDir);
        return true;
    }

    /**
     * 将数据写道指定文件
     * @param className
     * @param content
     * @param fileDir
     */
    private static void saveEntityFile(String className,String content,String fileDir) {

        fileDir = fileDir + "/" + className + "Controller" + CommonConstants.JAVA_FILE;
        FileUtil.writeString(content, fileDir, "UTF-8");
    }

    /**
     * 构建实体类
     * @param baseEntity
     * @param filePath
     * @return
     */
    private static String buildController(BaseEntity baseEntity, String filePath) {
        String content = ResourceUtil.readUtf8Str(filePath);
        if (StringUtils.isEmpty(content)) {
            return null;
        }
        content = content.replace("${AUTHOR}",baseEntity.getAuthor());
        content = content.replace("${DATE}", DateUtil.format(new Date(),"yyyy/MM/dd"));
        content = content.replace("${CLASS_NAME}",baseEntity.getClassName());
        content = content.replace("${ROUTE_NAME}", StrUtil.lowerFirst(baseEntity.getClassName()));
        return content;
    }

}
